package com.friend.chat.page.view.register

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import com.friend.chat.base.BaseActivity
import com.friend.chat.databinding.ActivityLoginBinding
import com.friend.chat.page.view.MainActivity
import com.friend.chat.page.vm.LoginViewModel
import com.friend.chat.utils.SPUtils
import org.jetbrains.anko.toast

class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {



    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, LoginActivity::class.java)
            activity.startActivity(intent)
        }
    }

    override fun yourViewModel(): LoginViewModel = LoginViewModel()

    override fun yourViewBing(): ActivityLoginBinding = ActivityLoginBinding.inflate(layoutInflater)

    override fun init() {
        val username = SPUtils.getInstance().getStringValue("username","")
        val password = SPUtils.getInstance().getStringValue("password","")
        if (username.isNotEmpty()){
            mViewBinding.etUsername.setText(username)
        }
        if (password.isNotEmpty()){
            mViewBinding.etPassword.setText(password)
        }

        mViewBinding.btnLogin.setOnClickListener {
            if (TextUtils.isEmpty(mViewBinding.etUsername.text)){
                toast("请输入用户名")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(mViewBinding.etPassword.text)){
                toast("请输入密码")
                return@setOnClickListener
            }
            mVModel.loginByPass(mViewBinding.etUsername.text.toString(),mViewBinding.etPassword.text.toString())
        }
        mVModel.userResponse.observe(this){
            SPUtils.getInstance().putStringValue("username",mViewBinding.etUsername.text.toString())
            SPUtils.getInstance().putStringValue("password",mViewBinding.etPassword.text.toString())
            var data = it.data
            mVModel.toast("登录成功")
            MainActivity.open(this)
            finish()
        }
    }
}